<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body>div {
            position: relative;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: skyblue;
            position: absolute;
        }
    </style>
</head>

<body>
    <div>
        <div class="box"></div>
    </div>

    <script>
        // 需求：让小方块向右移动200px
        //         向下移动200px
        //         向左移动200px
        //         向上移动200px

        let box = document.querySelector('.box')

        function move(end, p, cb) {
            // 计算步长
            if (p == 'left') {
                var start = box.offsetLeft
                offset$ = 'offsetLeft'
            } else if (p == 'top') {
                var start = box.offsetTop
                offset$ = 'offsetTop'

            }
            // 结束位置
            end
            // 设置时间
            let time = 5
            // 计算步长
            let dist = 6 * start > end ? -1 : 1

            let fn = setInterval(function () {
                if (Math.abs(box[offset$]) == Math.abs(end - start)) {

                    console.log(box[offset$])

                    box.style[p] = end - start + 'px'
                    clearInterval(fn)
                    console.log(cb)
                    cb()
                    return
                }
                box.style[p] = box[offset$] + dist + 'px'
            }, time)
        }
        move(300,'left', function() {
            console.log('完成第一步')
            move(300, 'top', function() {
                console.log('完成第二步')
                move(-300, 'left', function() {
                    console.log('完成第三步')
                    move(-300, 'top', function() {
                        console.log('完成第四步')
                    })
                })
            })
        })


        // // 计算步长
        // let start1 = box.offsetTop
        // console.log(start1)
        // // 结束位置
        // let end1 = 300
        // // 设置时间
        // let time1 = 60
        // // 计算步长
        // let dist1 = (end1 - start1) / time1

        // let fn1 = setInterval(function () {
        //     if (box.offsetTop >= (end1 - start1)) {
        //         box.style.top = end - start + 'px'
        //         clearInterval(fn1)
        //         return
        //     }
        //     box.style.top = box.offsetTop + dist1 + 'px'
        // }, time1)








    </script>
</body>

</html>